/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 2 -*- */
/**
* @file timer.cpp
* 
* Library for control the time elapsed.
*
* @author Miguel Ángel Vílchez López 2010 <sacra@openmatica.es>
*
* Idea got from cc.byexamples.com.
* @sa http://cc.byexamples.com/20070314/create-a-timer/
*
* Codigo is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* Codigo is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License along
* with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "timer.hpp"

CMTimer::CMTimer(unsigned long int usec)
{
  if ( usec >= 1000000 )
  {
		this->sec = (long int)(usec/1000000);
  	this->usec = (long int)(fmod(usec,1000000));
  }
  else
  {
		this->sec = 0;
		this->usec = usec;
	}
		
	this->setTimerUsec();
}

CMTimer::~CMTimer()
{}

void CMTimer::setTimerUsec()
{
	gettimeofday(&this->tv_end,NULL);
	if ((this->tv_end.tv_usec + this->usec) < 1000000)
	{
		this->tv_end.tv_usec += this->usec;
		this->tv_end.tv_sec += this->sec;
	}
	else
	{
		this->tv_end.tv_usec = (this->tv_end.tv_usec + this->usec - 1000000);
		this->tv_end.tv_sec += this->sec + 1;
	}	
}

int CMTimer::check()
{ 
	  struct timeval tv_now;  
	  gettimeofday(&tv_now,NULL);  

		//If seconds now are bigger than seconds end or seconds now = seconds end
		// and useconds now bigger or equal than useconds end
	  if( (tv_now.tv_sec > this->tv_end.tv_sec) || 
	  ( (tv_now.tv_sec == this->tv_end.tv_sec) && (tv_now.tv_usec >= this->tv_end.tv_usec) ) )
	  {
				this->setTimerUsec();
	      return 1;
	  }
	  else  
	      return 0;
	}
